package com.authine.cloudpivot.web.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.facade.IMMessageFacade;
import com.authine.cloudpivot.engine.api.model.im.MessageModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.enums.type.IMMessageChannelType;
import com.authine.cloudpivot.engine.enums.type.IMMessageType;
import com.authine.cloudpivot.web.api.dao.*;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.helper.FormSubmitHelper;
import com.authine.cloudpivot.web.api.service.AsyncDataService;
import com.authine.cloudpivot.web.api.service.FescoadQueryService;
import com.authine.cloudpivot.web.api.view.runtime.WorkItemSubmitVO;
import com.authine.cloudpivot.web.api.vo.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.authine.cloudpivot.web.api.view.runtime.WorkItemDataVO.FORM_TYPE_WF;

@Slf4j
@Service
public class FescoadQueryServiceImpl  implements FescoadQueryService {

    @Autowired
    private FescoadQueryMapper fescoadQueryMapper;

    @Autowired
    private FormSubmitHelper formSubmitHelper;

    @Autowired
    private  DubboConfigService dubboConfigService;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private DSRWJDMapper dsrwjdMapper;

    @Autowired
    private GSLXMapper gslxMapper ;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private XMKXXMapper xMKXXMapper ;

    @Autowired
    private XMQDMapper xmqdMapper;

    @Autowired
    private XZDJXQMapper xzdjxqMapper;

    @Autowired
    private TestMapper testMapper;

    @Autowired
    private XmlvllMapper xmlvllMapper;

    @Autowired
    private WHMDXXMapper whmdxxMapper;

    @Autowired
    private XMLXMapper xmlxMapper;
    @Autowired
    private ProjectTeamMapper projectTeamMapper;

    @Autowired
    private ExecutiveDetailsMapper executiveDetailsMapper;


    @Autowired
    private SubjectTypeBMapper subjectTypeBMapper;

    @Autowired
    private RecruitmentdemandMapper recruitmentdemandMapper;


    @Override
    public List<Map<String,Object>> selectStoreCity(String id) {


        return  fescoadQueryMapper.selectStoreCity(id);

    }

    /**
     * 反写的数据  工作项--项目名称  ，工时类型=否  ，项目编号=项目编号  ,工时类型=项目
     * @param objectId
     */
    @Override
    public void addDatToWorkTime(String objectId) {


        //获取项目可行 数据
        Xmkxx xmkxx = xMKXXMapper.selectXMKXX(objectId);

        GSLX gslx = new GSLX() ;
        gslx.setDetail(xmkxx.getSubjectName());
        gslx.setProjectNo(xmkxx.getProjectNo());
        gslx.setRoles(xmkxx.getSubjectPerson());

        gslxMapper.insertGSLX(gslx);


        //插入到工时类型中

    }
    /**
     * 项目立项 审批结束之后，更新 工时类型里 工时类型=是
     * 反写的数据  工作项--项目名称  ，工时类型=否  ，项目编号=项目编号  ,工时类型=项目
     * @param projectNo
     */
    @Override
    public void updateDatToWorkTime(String projectNo) {
        gslxMapper.updateDatToWorkTime(projectNo);
    }

    @Override
    public void startFlow(String objectId,String no) {
        if("yes".equals(no)){
            String url ="";
            String  content = "您有一条新的待办";
            Map<String,String>  s = xmqdMapper.selectRecruitmenOrStore(objectId);
            log.info("ssssss,{}",s.size());
            String subjectName = xMKXXMapper.getSubjectName(s.get("subjectName"));
            log.info("ssssss,{}",subjectName);
            //项目经理

            if(s.get("subjectPerson")!=null){
                List<Map> list1 = (List<Map>) JSON.parse( s.get("subjectPerson"));

                Map m1 = list1.get(0);
                String id1 = (String) m1.get("id");
                User user1 = userMapper.getUserId(id1);
                if(s.get("shopInspection")==null&&s.get("recruitment")==null){



                    log.info("组建团队需要发起流程");
                }else {
                    if("是".equals(s.get("shopInspection"))) {
                        url = "form/detail?startWorkflowCode=XZDJXQ";
                        sendMessage(user1.getUserId(), url, content,"请为"+subjectName+"新增店检需求");
                    }
                    if("是".equals(s.get("recruitment"))) {
                        url = "form/detail?startWorkflowCode=XZZPXQ";
                        sendMessage(user1.getUserId(), url, content,"请为"+subjectName+"新增招聘需求");
                    }
                }
            }

            //执行经理
            if(s.get("eManager")!=null){
                List<Map> list = (List<Map>) JSON.parse( s.get("eManager"));
                User  user = new User();
                for (int i = 0; i <list.size() ; i++) {
                    Map m = list.get(i);
                    String id = (String) m.get("id");
                    user =  userMapper.getUserId(id);
                    if(whmdxxMapper.getSubjectName(objectId)==null){
                        url = "form/detail?schemaCode=ProjectTeam&sheetCode=ProjectTeam";
                        sendMessage(user.getUserId(), url, content,"请为"+subjectName+"添加执行团队");
                    }else{
                        url = "form/detail?startWorkflowCode=storeList";
                        sendMessage(user.getUserId(), url, content,"请为"+subjectName+"门店督导信息列表");
                    }
                }
            }

        }

    }
    //流程编写
    public void startFlow(Map<String,String> s,String tableName){
        String workflowCode = tableName;
        String schemaCode = tableName;
        String formCode = tableName;

        WorkItemSubmitVO vo = new WorkItemSubmitVO();
        BizObjectModel bom = new BizObjectModel();
        bom.setSchemaCode(schemaCode);
        bom.setFormCode(formCode);
        bom.setSequenceStatus(SequenceStatus.PROCESSING.toString());
        Map<String, Object> data = bom.getData();
        //data数据暂时不设置
        data.put("projectNo","11111");
        //
        vo.setBizObject(bom);
        vo.setFormType(FORM_TYPE_WF);
        vo.setAgree(true);
        vo.setDepatmentId(userMapper.getDepId(s.get("creater")));
        vo.setOwner(s.get("creater"));
        vo.setWorkflowCode(workflowCode);
        formSubmitHelper.submit(vo,s.get("creater"),schemaCode);
    }


    @Override
    public Integer getProjectNo(String type) {
        log.info("type---------------{}",type);
        Integer projectNo = xMKXXMapper.getProjectNo(type);
        log.info("type---------------{}",projectNo);

        return projectNo;
    }

    @Override
    public void updateProjectNo(String id, String projectNo,Integer code) {
        xMKXXMapper.updateProjectNo(id,projectNo,code);
    }

    @Override
    public void updateSubjectStatus(String projectNo,String id) {
        log.info("更新项目立项，项目可行性，工时类型----》，{}",id);
        xmqdMapper.updateSubjectStatus(projectNo);
        gslxMapper.updateSubjectStatusGSLX(projectNo);
        xMKXXMapper.updateSubjectStatus(id);
    }

    @Override
    public void updateOrInsertTask(String bizObjectId) {
        Xmlvll xmlvll = xmlvllMapper.selectXMLVLL(bizObjectId);

        if("是".equals(xmlvll.getFinished())){
            //首先查询 定时任务进度表
            DSRWJD dsrwjd = dsrwjdMapper.selectTask(xmlvll.getProjectnames(),xmlvll.getServiceModule(),xmlvll.getServiceItem(),xmlvll.getRealizationWay());
            String uuid = "";
            Map map = new HashMap<>();
            List<Attachment> attachment = new ArrayList<>();
            map.put("id",xmlvll.getCreater());
            map.put("type",3);
            attachment = attachmentMapper.getAttachment(bizObjectId,"attachment");
            if(dsrwjd==null){ //插入操作
                List<Map> list = new ArrayList<>();
                list.add(map);
                //查询附件表
                uuid =  generationId("iden7_DSRWJD");
                //插入任务表
                DSRWJD d = new DSRWJD();
                d.setName(xmlvll.getName());
                d.setId(uuid);
                d.setCreatedDeptId(xmlvll.getCreateddeptid());
                d.setOwner(xmlvll.getOwner());
                d.setCreatedTime(xmlvll.getModifiedtime());
                d.setModifiedTime(xmlvll.getModifiedtime());
                d.setCreater(xmlvll.getCreater());
                d.setOwnerDeptId(xmlvll.getOwnerdeptid());
                d.setSubjectName(xmlvll.getProjectnames());
                d.setProjectNo(xmlvll.getProjectno());
                d.setServiceModule(xmlvll.getServiceModule());
                d.setServiceItem(xmlvll.getServiceItem());
                d.setRealizationWay(xmlvll.getRealizationWay());
                d.setSequenceStatus(xmlvll.getSequencestatus());
                d.setRoles(JSON.toJSONString(list));
                dsrwjdMapper.insertTask(d);
                //插入到附件表中
                if(attachment !=null) {
                    insertAttactment(attachment, uuid, xmlvll.getCreater());
                }
            }else{//跟新操作
                //人员插入
                List<Map> list = (List<Map>) JSON.parse(dsrwjd.getRoles());
                Boolean flag = true;
                for (int i = 0; i <list.size() ; i++) {
                    if((!map.get("id").equals(list.get(i).get("id")))&&flag){
                        list.add(map);
                        flag = true;
                    }
                }
                dsrwjd.setRoles(JSON.toJSONString(list));
                dsrwjdMapper.updateTaskRoleById(dsrwjd.getId(),dsrwjd.getRoles());
                //附件插入
                if(attachment !=null) {
                    insertAttactment(attachment, dsrwjd.getId(), xmlvll.getCreater());
                }
            }
        }

    }

    @Override
    public String getStoreRotation(String storeRotation) {
        return xzdjxqMapper.getStoreRotation(storeRotation);
    }

    @Override
    public void lxNotification(String id,String subjectName) {
        log.info("项目立项开始----------------");
        String content = "项目立项";
        String url = "form/detail?startWorkflowCode=XMQD&return=/workflow-center/start-workflow";
        sendMessage(userMapper.getUserId(id).getUserId(),url,content,subjectName+"  "+content);
        log.info("项目立项结束----------------");
    }

    @Override
    public void closeSuject(String id) {
        xMKXXMapper.updateSubjectStatus(id);
    }

    @Override
    public void getUs() {
        userMapper.getu();
    }

    @Override
    public void bachInsert() {
        log.info("导入开始");
       List<Xmkxx> list =  xMKXXMapper.selectXMKXXAll();

        for (int i = 0; i < list.size(); i++) {
            GSLX gslx = new GSLX() ;
            gslx.setDetail(list.get(i).getSubjectName());
            gslx.setProjectNo(list.get(i).getProjectNo());
            gslx.setRoles(list.get(i).getSubjectPerson());
            gslxMapper.insertGSLX(gslx);
            xMKXXMapper.updateBach(list.get(i).getId());
        }
        log.info("导入结束");



    }

    @Override
    public void bachInsertX() {

        Map<String, String> stringStringMap = xMKXXMapper.selectXMKXXByBach();
        for (int i = 0; i <stringStringMap.size() ; i++) {
            xMKXXMapper.updateSubjectStatus(stringStringMap.get("subjectName"));
            xMKXXMapper.updateBachInsert(stringStringMap.get("id"));
        }


    }

    @Override
    public void updateSubjectStatusX() {
        Map<String, String> stringStringMap = xMKXXMapper.updateSubjectStatusX();

        if(stringStringMap!=null){
            for (int i = 0; i < stringStringMap.size(); i++) {
                xmqdMapper.updateSubjectStatus(stringStringMap.get("subjectNo"));
                gslxMapper.updateSubjectStatusGSLX(stringStringMap.get("subjectNo"));
                xMKXXMapper.updateSubjectStatus(stringStringMap.get("subjectName"));
                xMKXXMapper.updateSubjectStatusXX(stringStringMap.get("id"));
            }
        }
    }

    @Override
    public void insertXMLX() {

       List<XMQD> xmlvll = xmqdMapper.getAll();

        for (int i = 0; i < xmlvll.size(); i++) {
            startFlow(xmlvll.get(i).getId(),"no");
            updateDatToWorkTime(xmlvll.get(i).getProjectno());
            xmqdMapper.updateBachInser(xmlvll.get(i).getId());
        }
    }

    @Override
    public void lxNotificationBachInsert() {
       List<XMLX> list=  xMKXXMapper.getAll();
        for (int i = 0; i < list.size(); i++) {
            List<Map> list1 = (List<Map>) JSON.parse(list.get(i).getSubjectperson());
            Map m = list1.get(0);
            String staffingHRId = (String) m.get("id");
            lxNotification(staffingHRId,list.get(i).getSubjectname());
            xMKXXMapper.updateXMKXXStatus(list.get(i).getProjectno());
            xMKXXMapper.updateXMVL(list.get(i).getId());
        }
    }
    //获取项目可行性编码
    @Override
    public void getSubjectCode(String id, String subjectCode) {
        //先休眠
        //asyncDataService.getSubjectCode();

        log.info("进入这个方法后 获取到的 subjectCode={}",subjectCode);
        //查出來编码-subjectCode
        SubjectTypeB subjectTypeB = subjectTypeBMapper.getsubjectNumber(subjectCode);
        String num = subjectTypeB.getSubjectNumber();
        //组装编码
        Date date = new Date();//此时date为当前的时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//设置当前时间的格式，为年-月-日
        //修改编码，将编码+1
        int countNum = Integer.parseInt(num) + 1;
        subjectTypeBMapper.updatesubjectNumber(subjectCode,String.valueOf(countNum));
        //生成编码
        String bm = subjectTypeB.getSubjectCode() + dateFormat.format(date) + String.format("%04d", Integer.parseInt(num));
        //修改projectNo
        xmqdMapper.updateProjectNo(id,bm);
        log.info("进入这个方法后 方法执行结束 subjectCode={}",subjectCode);
    }

    //每年将编码归1
    @Override
    public void updateToSubjectNumber(){
        subjectTypeBMapper.updateToSubjectNumber();
    }

    @Override
    public List<Recruitmentdemand> checkSubjectStatus(String projectName) {
        return recruitmentdemandMapper.getlist(projectName);
    }

    @Override
    public void updateTime(String id, Date demandEndTime) {
        recruitmentdemandMapper.updateTime(id,demandEndTime);
    }

    @Override
    public Map<String, Object> getAttMessage(String refId) {
        return fescoadQueryMapper.getAttMessage(refId);
    }

    @Override
    public void inserData(String objectId) {
       XMQD xmqd =  xmqdMapper.getProject(objectId);
        xmqd.setName("组建团队-"+xmqd.getName().split("-")[1]);
        List<Map> list = (List<Map>) JSON.parse( xmqd.getEmanager());
        for (int j = 0; j < list.size(); j++) {
            List list1 = new ArrayList();
            Map m = list.get(j);
            String id = (String) m.get("id");
            Map map = new HashMap();
            map.put("id",id);
            map.put("type","3");
            list1.add(map);
            String s = JSON.toJSONString(list1);
            String ids = generationId("iden7_ProjectTeam");
            xmqd.setName("组建团队-"+xmqd.getName().split("-")[1]);
            projectTeamMapper.insertProject(xmqd.getCreater(),xmqd.getOwner(),xmqd.getCreateddeptid(),xmqd.getOwnerdeptid(),
                    xmqd.getProjectno(),xmqd.getName(),ids,xmqd.getId(),s,"执行经理",xmqd.getSubjectstarttime(),xmqd.getSubjectendtime(),xmqd.getCreatedtime());

            xmqd.setName("执行明细-"+xmqd.getName().split("-")[1]);
            executiveDetailsMapper.insertProject(ids,xmqd.getName(),xmqd.getCreater(),xmqd.getOwner(),xmqd.getCreateddeptid(),xmqd.getOwnerdeptid(),
             xmqd.getProjectno(), generationId("iden7_ExecutiveDetails"),xmqd.getId(),s,"执行经理",xmqd.getSubjectstarttime(),xmqd.getSubjectendtime(),xmqd.getCreatedtime());
        }



    }

    public void insertAttactment(List<Attachment> attachment,String taskId,String creater){
        for (int i = 0; i <attachment.size() ; i++) {
            attachment.get(i).setId(generationId("h_biz_attachment"));
            attachment.get(i).setBizPropertyCode("attachment");
            attachment.get(i).setBizObjectId(taskId);
            attachment.get(i).setCreater(creater);
            attachment.get(i).setSchemaCode("DSRWJD");
        }
        attachmentMapper.inserAttachment(attachment);
    }


    public String generationId(String tableName){
      String   uuid  = UUID.randomUUID().toString().replace("-","");

     String uuid1 = testMapper.selectTableById(uuid,tableName);
      if(uuid1 != null){
          generationId(tableName);
      }
        return uuid;
    }

    /**
     * @Description : 发送钉钉待办通知
     * @param ： receivers
     */
    public void sendMessage(String receivers,String url,String content,String titele){
        log.info("发起流程,{}",content);
        IMMessageFacade imMessageFacade =this.dubboConfigService.getImMessageFacade();

        MessageModel messageModel = new MessageModel();

        messageModel.setReceivers(receivers);
        messageModel.setUrl(url);
        messageModel.setChannel(IMMessageChannelType.DINGTALK);
        messageModel.setMessageType(IMMessageType.BUSINESS_REMIND);
        messageModel.setContent(content);
        messageModel.setTitle(titele);
        String[] split = receivers.split(",");
        for (String userId : split) {
            String name = userMapper.getNameById(userId);
            BizObjectModel objectModel = new BizObjectModel();
            objectModel.setSchemaCode("message");
            objectModel.setSequenceStatus("COMPLETED");
            Map<String, Object> data = objectModel.getData();
            data.put("user",name);
            data.put("titele",titele);
            data.put("message",content);
            dubboConfigService.getBizObjectFacade().saveBizObject(userId,objectModel,false);
        }
        imMessageFacade.sendMessage(messageModel);
    }

    /**
     * @Description : 发送钉钉待办通知
     * @param ： receivers
     */
    public void sendTextMessage(String receivers,String url,String content, String titele){
        log.info("发起流程,{}",content);
        IMMessageFacade imMessageFacade =this.dubboConfigService.getImMessageFacade();

        MessageModel messageModel = new MessageModel();
        //messageModel.setWorkItemIdOrObjectId(workItemIdOrObjectId);
        //messageModel.setWorkflowInstanceId(workflowInstanceId);
        messageModel.setReceivers(receivers);
        messageModel.setUrl(url);
        messageModel.setChannel(IMMessageChannelType.DINGTALK);
        messageModel.setMessageType(IMMessageType.BUSINESS_REMIND);
        messageModel.setContent(content);
        messageModel.setTitle(titele);
        String[] split = receivers.split(",");
        for (String userId : split) {
            String name = userMapper.getNameById(userId);
            BizObjectModel objectModel = new BizObjectModel();
            objectModel.setSchemaCode("message");
            objectModel.setSequenceStatus("COMPLETED");
            Map<String, Object> data = objectModel.getData();
            data.put("user",name);
            data.put("titele",titele);
            data.put("message",content);
            dubboConfigService.getBizObjectFacade().saveBizObject(userId,objectModel,false);
        }
        imMessageFacade.sendTextMessage(messageModel);
    }


}



